#include "ChooseDialog.h"
#include <iostream>
#include <sstream>


ChooseDialog::ChooseDialog(QWidget* parent /*= 0*/, Qt::WindowFlags flags /*= 0*/)
{
    ui.setupUi(this);
}

ChooseDialog::~ChooseDialog()
{

}

int ChooseDialog::chooseDevice(QString& deviceName, QWidget* parent /*= 0*/)
{
    ChooseDialog dialog(parent);
    videoInput* capture = &videoInput::getInstance();
    int nDevices = capture->listDevices(true);
    if(nDevices < 1)
    {
        std::cerr << "No Webcam was found.\n";
        return -1;
    }

    for(int i = 0; i < nDevices; ++i)
    {
        wchar_t* deviceName = capture->getNameVideoDevice(i);
        QListWidgetItem* newItem = new QListWidgetItem(QString::fromWCharArray(deviceName), dialog.ui.listWidget);
        newItem->setData(1, i);
    }
    dialog.ui.listWidget->setCurrentRow(0);

    if(dialog.exec() == QDialog::Accepted)
    {
        QList<QListWidgetItem*> selectedItemList = dialog.ui.listWidget->selectedItems();
        QVariant role0 = selectedItemList.first()->data(0);
        deviceName = role0.toString();
        QVariant role1 = selectedItemList.first()->data(1);
        return role1.toInt();
    }
    return -1; // dummy return
}

int ChooseDialog::chooseFormat(int captureDeviceIdx, QWidget* parent /*= 0*/)
{
    ChooseDialog dialog(parent);
    dialog.setWindowTitle("Choose Format");
    videoInput* capture = &videoInput::getInstance();
    unsigned int nFormats = capture->getCountFormats(captureDeviceIdx);

    for(unsigned int i = 0; i < nFormats; ++i)
    {
        MediaType type = capture->getFormat(captureDeviceIdx, i);
        std::wstringstream sstream;
        sstream << "size frame: " << type.width << " x " << type.height << ", "
                << "framerate: " << type.MF_MT_FRAME_RATE << " fps, TypeVideoStream: " << type.pMF_MT_SUBTYPEName
                << ", VIDEO_LIGHTING: " << type.MF_MT_VIDEO_LIGHTING << std::endl;

        QListWidgetItem* newItem = new QListWidgetItem(QString::fromWCharArray(sstream.str().c_str()), dialog.ui.listWidget);
        newItem->setData(1, i);
    }

    dialog.ui.listWidget->setCurrentRow(0);

    if(dialog.exec() == QDialog::Accepted)
    {
        QList<QListWidgetItem*> selectedItemList = dialog.ui.listWidget->selectedItems();
        QVariant value = selectedItemList.first()->data(1);
        return value.toInt();
    }
    return -1; // dummy return
}
